package com.itheima.controller;

import com.itheima.result.R;
import com.itheima.vo.UploadVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @projectName: kafka
 * @package: com.itheima.controller
 * @className: UploadController
 * @author: Eric
 * @description: TODO
 * @date: 2023/9/25 20:31
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @PostMapping("/upload")
    public R<?> upload(MultipartFile file){
        try {
            String originalFilename = file.getOriginalFilename();   // 1.获取源文件的名字
            String perfix = originalFilename.substring(originalFilename.lastIndexOf("."));      // 2.截取源文件的后缀( Xxx.jdp或者Xxx.png)
            String newFileName = UUID.randomUUID().toString() + perfix;    // 3.用UUID生成新的前缀名(防止出现重复的)
            file.transferTo(new File("F:\\Git\\youdianda\\nginx-youdianda\\html\\backend\\undefined\\" + newFileName));

            UploadVO uploadVO = new UploadVO();
            uploadVO.setSavePath("\\"+newFileName);
            uploadVO.setName("newFileName");
            return R.success(uploadVO);
        } catch (RuntimeException | IOException e) {
            log.info("文件上传失败");
        }
        return R.error("文件上传失败");
    }
}
